#!/bin/bash
<<comment
SCRIPYT:Historical_connection_monitoring.sh
AUTHOR:kaipengcheng@hcis.com.cn
DATE:2023-02-08
DESCRIBE:监控Redis外部客户端访问的时间、ip地址以及端口，日志保存路径：/root/Historical_connection_monitoring.log
SYSTEM:CentOS 7
VERSION:1.0.0
MODIFY:想要获取真实IP，需要开启Redis透传
comment

#安装redis-cli
wget http://download.redis.io/redis-stable.tar.gz
tar -xvzf redis-stable.tar.gz
yum -y install gcc gcc-c++ libstdc++-deve
cd redis-stable
make
make MALLOC=libc
#注：该redis-cli版本需二次编译,不然报错
make
make MALLOC=libc
cp src/redis-cli /usr/local/bin/

#定义变量
#更改为Redis的IP
REDIS_HOST=10.136.255.219

#Redis端口
REDIS_PORT=6379

#日志保存路径：/root/Historical_connection_monitoring.log
LOG_FILE=~/Historical_connection_monitoring.log

#Redis密码，请自行更改！！！
REDIS_PASSWORD=Kpc123!!

#提取内容存入日志

redis-cli -h $REDIS_HOST -p $REDIS_PORT -a $REDIS_PASSWORD -c monitor | while read line; do
  if echo $line | grep -E [0-9]+:[0-9]+; then
    ip=$(echo $line | awk -F "]" '{print $1}' |awk '{print $3}')
    echo "$(date +%Y-%m-%d_%H:%M:%S) $ip " >> $LOG_FILE
  fi
done 
